<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: functions_troubleshooter.php,v $ : $Revision: 1.12 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Inserts a new Troubleshooter Category
*/
function insertTroubleshooterCat($title, $description, $displayorder, $tgroupidlist, $norender = false)
{
	global $dbCore;

	// First insert the troubleshooter category
	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."troubleshootercat` (`staffid`, `title`, `description`, `dateline`, `displayorder`, `views`) VALUES ('". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($title) ."', '". $dbCore->escape($description) ."', '". DATENOW ."', '". intval($displayorder) ."', '0');");
	$troubleshootercatid = $dbCore->lastInsertId();
	if (!$troubleshootercatid)
	{
		return false;
	}

//	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."troubleshootercatdata` (`troubleshootercatid`, `contents`) VALUES ('". intval($troubleshootercatid) ."', '". $dbCore->escape($contents) ."');");

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_TROUBLESHOOTER, $troubleshootercatid, false);

	return $troubleshootercatid;
}

/**
* Update an existing categories values
*/
function updateTroubleshooterCat($troubleshootercatid, $title, $description, $displayorder, $views, $tgroupidlist)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."troubleshootercat` SET `staffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `title` = '". $dbCore->escape($title) ."', `description` = '". $dbCore->escape($description) ."', `dateline` = '". DATENOW ."', `displayorder` = '". intval($displayorder) ."', `views` = '". intval($views) ."' WHERE `troubleshootercatid` = '". intval($troubleshootercatid) ."';");

//	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."troubleshootercatdata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `troubleshootercatid` = '". intval($troubleshootercatid) ."';");

	insertTemplateGroupAssignLink($tgroupidlist, TGROUP_TROUBLESHOOTER, $troubleshootercatid, true);

	return true;
}

/**
* Deletes a list of troubleshooter categories and all responses below them
*/
function deleteTroubleshooterCat($troubleshootercatidlist)
{
	global $dbCore;

	if (!_is_array($troubleshootercatidlist))
	{
		return false;
	}

	// First delete the categories
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshootercat` WHERE `troubleshootercatid` IN (". buildIN($troubleshootercatidlist) .");");

	// Delete all steps
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshootersteps` WHERE `troubleshootercatid` IN (". buildIN($troubleshootercatidlist) .");");

	// Delete all the links
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshooterlinks` WHERE `troubleshootercatid` IN (". buildIN($troubleshootercatidlist) .");");

	deleteTemplateGroupAssignLinks($troubleshootercatidlist, TGROUP_TROUBLESHOOTER);

	return true;
}

/**
* Renders the troubleshooter category form for insert/edit
*/
function renderTroubleshooterCatForm($type)
{
	global $_SWIFT, $dbCore;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["tscatdetails"]);

	// Title
	printTextRow("title", $_SWIFT["language"]["tscattitle"], $_SWIFT["language"]["desc_tscattitle"], "text", $_POST["title"]);

	// Description
	printTextareaRow("description", $_SWIFT["language"]["tscatdesc"], $_SWIFT["language"]["desc_tscatdesc"], $_POST["description"], 50);
	
	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the troubleshooter category.. will be done only for insert action
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."troubleshootercat` ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}		
	}
	printNumberRow("displayorder", $_SWIFT["language"]["tscatdisporder"], $_SWIFT["language"]["desc_tscatdisporder"], $_POST["displayorder"]);

	// Views
	if ($type == EDIT)
	{
		printNumberRow("views", $_SWIFT["language"]["tscatviews"], $_SWIFT["language"]["desc_tscatviews"], $_POST["views"]);		
	}

	printTGroupRow("tgroupid", $_SWIFT["language"]["templategroups"], $_SWIFT["language"]["desc_templategroups"], $type, TGROUP_TROUBLESHOOTER, $_POST["troubleshootercatid"]);

//	printhtmlAreaRow("contents", $_SWIFT["language"]["contents"], $_POST["contents"], 25, getTRHtmlArea());

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["inserttscat"], $_SWIFT["language"]["updatetscat"]));

	printMainTableFooter();

	addHiddenField("_m", "troubleshooter");
	addHiddenField("_a", iif($type==INSERT, "insertcategory", "editcategory"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("troubleshootercatid", $_POST["troubleshootercatid"]);
	}
	printFormEnd();
}

/**
* Builds a category array of troubleshooter
*/
function buildTSCategoryData($tscatidlist, $dodata = false)
{
	global $dbCore, $_SWIFT;

	// We first fetch all the troubleshooter steps that are under the category list
	$steplist = $stepdata = array();
	if ($dodata)
	{
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."troubleshootersteps` AS troubleshootersteps LEFT JOIN `". TABLE_PREFIX ."troubleshooterdata` AS troubleshooterdata ON (troubleshootersteps.troubleshooterid = troubleshooterdata.troubleshooterid) WHERE troubleshootersteps.troubleshootercatid IN (". buildIN($tscatidlist) .");");		
	} else {
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."troubleshootersteps` WHERE `troubleshootercatid` IN (". buildIN($tscatidlist) .");");
	}
	while ($dbCore->nextRecord())
	{
		$steplist[$dbCore->Record["troubleshooterid"]] = $dbCore->Record;
	}

	// Now that we have the list of all steps, we first begin with the foremost link ie parenttroubleshooterid==0 and then move through it to fetch sub links.
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."troubleshooterlinks` WHERE `troubleshootercatid` IN(". buildIN($tscatidlist) .") ORDER BY `parenttroubleshooterid` ASC;");
	while ($dbCore->nextRecord())
	{
		$stepdata[$dbCore->Record["troubleshootercatid"]][$dbCore->Record["parenttroubleshooterid"]][] = $steplist[$dbCore->Record["childtroubleshooterid"]];
	}

	return $stepdata;
}


/**
* Does a loop on categories to generate tree view data
*/
function doTSCategoryTreeLoop($troubleshootercatid, $data, $parentid, &$nodeclass, $selectedcatid=0)
{
	global $_SWIFT;

	$childcount = count($data[$troubleshootercatid][$parentid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		// We itterate through all the childs
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$troubleshootercatid][$parentid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($data[$troubleshootercatid][$childdata["troubleshooterid"]]);

			// Add this node to our parent node
			$_newnode = &$nodeclass->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $childdata["subject"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ <a href='index.php?_m=troubleshooter&_a=insertstep&troubleshootercatid=". $troubleshootercatid ."&parenttroubleshooterid=". $childdata["troubleshooterid"] ."' id='blue' title='". $_SWIFT["language"]["addstep"] ."'>". $_SWIFT["language"]["addstep"] ."</a> | <a href='index.php?_m=troubleshooter&_a=editstep&troubleshooterid=". $childdata["troubleshooterid"] ."' id='blue' title='". $_SWIFT["language"]["editstep"] ."'>". $_SWIFT["language"]["editstep"] ."</a> | <a onClick='javascript:doConfirm(\"". $_SWIFT["language"]["stepdelconfirmmsg"] ."\", \"index.php?_m=troubleshooter&_a=managesteps&do=delete&troubleshooterid=". $childdata["troubleshooterid"] ."\");' href='#' id='blue' title='". $_SWIFT["language"]["delete"] ."'>". $_SWIFT["language"]["delete"] ."</a> ]", 'link' => "", 'icon' => "icon_graybigdot.gif", 'expandedIcon' => iif(!$subchilds, "icon_bluebigdot.gif", "icon_bluebigdot.gif"), 'expanded' => true)));

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				// Yup, do another loop for this
				$index++;
				doTSCategoryTreeLoop($troubleshootercatid, $data, $childdata["troubleshooterid"], $_newnode, $selectedcatid);
			}
		}
	}
	
	return true;
}

/**
* Builds a treeview like category select data
*/
function buildTSCategorySelectData($troubleshootercatid, $selectedcatid=0)
{
	global $_SWIFT, $dbCore;

	// Get the data for this troubleshooter category
	$_troubleshootercat = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."troubleshootercat` WHERE `troubleshootercatid` = '". intval($troubleshootercatid) ."';");
	if (empty($_troubleshootercat["troubleshootercatid"]))
	{
		return false;
	}

	// Now fetch all the data for this troubleshooter category
	$categorydata = buildTSCategoryData(array($troubleshootercatid));

	// Build the tree for this category
	$_option = array();
	$indent = $index = 1;
	doTSCategoryOptionLoop($troubleshootercatid, $categorydata, 0, $selectedcatid, 1, $index, $_option);

	$_option[0]["title"] = $_troubleshootercat["title"];
	$_option[0]["value"] = "0";
	$_option[0]["selected"] = iif($selectedcatid==0, true, false);

	return $_option;
}

/**
* Does a loop on categories to generate data
*/
function doTSCategoryOptionLoop($troubleshootercatid, $data, $parentid, $selectedcatid=0, $indent, &$index, &$_option)
{
	$childcount = count($data[$troubleshootercatid][$parentid]);
	if (!is_array($_option))
	{
		$_option = array();
	}

	if ($childcount != 0)
	{
		$childindent = str_repeat("  ", $indent);
		$childprefix = $childindent."|- ";

		// Iterate through all childs and build the option list
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$troubleshootercatid][$parentid][$ii];
			$_option[$index]["title"] = $childprefix.$childdata["subject"];
			$_option[$index]["value"] = $childdata["troubleshooterid"];
			$_option[$index]["selected"] = iif($selectedcatid == $childdata["troubleshooterid"], true, false);
			$index++;
//			print_r($_option);

			// Does it have any sub childs?
			
			if (count($data[$troubleshootercatid][$childdata["troubleshooterid"]]) > 0)
			{
				// Yup, do another loop for this
				doTSCategoryOptionLoop($troubleshootercatid, $data, $childdata["troubleshooterid"], $selectedcatid, ($indent+1), $index, $_option);
			}
		}
	}
	
	return $_option;
}

/**
* Renders the Insert/Edit Troubleshooter Step Form
*/
function renderStepForm($type, $troubleshootercat, $_links = array())
{
	global $_SWIFT, $dbCore;

	printFormStart();
	printMainTableHeader($_SWIFT["language"]["stepdetails"]);

	// Subject
	printTextRow("subject", $_SWIFT["language"]["tssubject"], $_SWIFT["language"]["desc_tssubject"], "text", htmlspecialchars($_POST["subject"]));

	// Display Order
	if ($type == INSERT)
	{
		// Get the last display order of the troubleshooter steps
		$_disporder = $dbCore->queryFetch("SELECT `displayorder` FROM `". TABLE_PREFIX ."troubleshootersteps` WHERE `troubleshootercatid` = '". intval($troubleshootercat["troubleshootercatid"]) ."' ORDER BY `displayorder` DESC LIMIT 1;");
		if (empty($_disporder["displayorder"]))
		{
			$_POST["displayorder"] = 1;
		} else {
			$_POST["displayorder"] = $_disporder["displayorder"]+1;
		}
	}
	printNumberRow("displayorder", $_SWIFT["language"]["tsdisporder"], $_SWIFT["language"]["desc_tsdisporder"], $_POST["displayorder"]);

	if (!empty($_GET["parenttroubleshooterid"]))
	{
		$selectedcatid = $_GET["parenttroubleshooterid"];
	} else {
		$selectedcatid = 0;
	}

	$_options = buildTSCategorySelectData($troubleshootercat["troubleshootercatid"], $selectedcatid);
	if (count($_links))
	{
		foreach ($_options as $key=>$val)
		{
			if (in_array($val["value"], $_links))
			{
				$_options[$key]["selected"] = true;
			} else {
				$_options[$key]["selected"] = false;
			}
		}
	}

	printSelectMultipleRow("links", $_SWIFT["language"]["tslinks"], $_SWIFT["language"]["desc_tslinks"], $_options, 5, "100%");

	printhtmlAreaRow("contents", $_SWIFT["language"]["contents"], $_POST["contents"], 25, getTRHtmlArea());

	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insertstep"], $_SWIFT["language"]["updatestep"]));

	printMainTableFooter();

	addHiddenField("_m", "troubleshooter");
	addHiddenField("_a", iif($type==INSERT, "insertstep", "editstep"));
	addHiddenField("step", "1");
	addHiddenField("troubleshootercatid", $troubleshootercat["troubleshootercatid"]);
	if ($type == EDIT)
	{
		addHiddenField("troubleshooterid", $_POST["troubleshooterid"]);
	}
	printFormEnd();
}

/**
* Inserts a new Troubleshooter Step
*/
function insertStep($troubleshootercatid, $subject, $displayorder, $contents, $links)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."troubleshootersteps` (`troubleshootercatid`, `staffid`, `subject`, `dateline`, `edited`, `editedstaffid`, `displayorder`, `views`) VALUES ('". intval($troubleshootercatid) ."', '". intval($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($subject) ."', '". DATENOW ."', '0', '0', '". intval($displayorder) ."', '0');");
	$troubleshooterid = $dbCore->lastInsertId();
	if (!$troubleshooterid)
	{
		return false;
	}

	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."troubleshooterdata` (`troubleshooterid`, `contents`) VALUES ('". intval($troubleshooterid) ."', '". $dbCore->escape($contents) ."');");

	// Now add the links
	$linksql = array();
	foreach ($links as $key=>$val)
	{
		$linksql[] = "('". intval($troubleshootercatid) ."', '". intval($val) ."', '". intval($troubleshooterid) ."')";
	}

	if (count($linksql))
	{
		$dbCore->shutdownQuery("REPLACE INTO `". TABLE_PREFIX ."troubleshooterlinks` (`troubleshootercatid`, `parenttroubleshooterid`, `childtroubleshooterid`) VALUES ". implode(",", $linksql).";");
	}

	return $troubleshooterid;
}

/**
* Update a Troubleshooter Step
*/
function updateStep($troubleshooterid, $troubleshootercatid, $subject, $displayorder, $contents, $links)
{
	global $dbCore, $_SWIFT;

	if (!_is_array($links))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."troubleshootersteps` SET `subject` = '". $dbCore->escape($subject) ."', `edited` = '". DATENOW ."', `editedstaffid` = '". intval($_SWIFT["staff"]["staffid"]) ."', `displayorder` = '". intval($displayorder) ."' WHERE `troubleshooterid` = '". intval($troubleshooterid) ."';");

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."troubleshooterdata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE `troubleshooterid` = '". intval($troubleshooterid) ."';");

	// Now add the new links
	$linksql = array();
	$nodelete = false;
	foreach ($links as $key=>$val)
	{
		// Make sure we arent linking to ourself.
		if ($val != $troubleshooterid)
		{
			$linksql[] = "('". intval($troubleshootercatid) ."', '". intval($val) ."', '". intval($troubleshooterid) ."')";			
		} else {
			$nodelete = true;			
		}
	}

	if (!$nodelete)
	{
		// Delete existing links first
		$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshooterlinks` WHERE `childtroubleshooterid` = '". intval($troubleshooterid) ."';");		
	}

	if (count($linksql))
	{
		$dbCore->shutdownQuery("REPLACE INTO `". TABLE_PREFIX ."troubleshooterlinks` (`troubleshootercatid`, `parenttroubleshooterid`, `childtroubleshooterid`) VALUES ". implode(",", $linksql).";");
	}

	return true;
}

/**
* Fetches the ids of all child steps under a given troubleshooter step
*/
function fetchChildSteps($troubleshooterid, $tslist = "")
{
	global $dbCore;

	if (empty($tslist))
	{
		$tslist = array();
	}

	$newlist = array();

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."troubleshooterlinks` WHERE `parenttroubleshooterid` = '". intval($troubleshooterid) ."';");
	while($dbCore->nextRecord()) {
		if (!in_array($dbCore->Record["childtroubleshooterid"], $tslist))
		{
			$tslist[] = $dbCore->Record["childtroubleshooterid"];
			$newlist[] = $dbCore->Record["childtroubleshooterid"];
		}
	}

	if (_is_array($newlist))
	{
		foreach ($newlist as $key=>$val)
		{
			fetchChildSteps($val, $tslist);
		}
	}

	return $tslist;
}

/**
* Deletes a specific troubleshooter step and all child steps under it
*/
function deleteSteps($troubleshooterid)
{
	global $dbCore;

	// Fetch all the steps
	$stepidlist = fetchChildSteps($troubleshooterid);
	if (!in_array($troubleshooterid, $stepidlist))
	{
		$stepidlist[] = $troubleshooterid;		
	}

	// First delete all the steps
	$steplist = buildIN($stepidlist);
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshootersteps` WHERE `troubleshooterid` IN (". $steplist .");");

	// Now delete all the contents
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshooterdata` WHERE `troubleshooterid` IN (". $steplist .");");

	// Now delete all the links that might exist
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."troubleshooterlinks` WHERE `parenttroubleshooterid` IN (". $steplist .") OR `childtroubleshooterid` IN (". $steplist .");");

	return count($stepidlist);
}

/**
* Builds the XML for troubleshooter
*/
function buildXMLTroubleshooter($troubleshootercatid, $data, $parentid, &$xmlclass)
{
	global $_SWIFT;

	$childcount = count($data[$troubleshootercatid][$parentid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		// We itterate through all the childs
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$troubleshootercatid][$parentid][$ii];
			$index = $ii+$index;

			// Check the count of subchilds for this
			$subchilds = count($data[$troubleshootercatid][$childdata["troubleshooterid"]]);

			// Add this node to our parent node
			$xmlclass->addParentTag("step");
			$xmlclass->addTag("subject", $childdata["subject"]);
			$xmlclass->addTag("displayorder", $childdata["displayorder"]);
			$xmlclass->addTag("contents", $childdata["contents"]);

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				// Yup, do another loop for this
				$index++;
				buildXMLTroubleshooter($troubleshootercatid, $data, $childdata["troubleshooterid"], $xmlclass);
			}
			$xmlclass->endParentTag("step");
		}
	}
	
	return true;
}

/**
* Renders the Category List
*/
function renderCategoryList()
{
	global $dbCore, $template;

	$mcategories = array();
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."troubleshootercat`;");
	while ($dbCore->nextRecord())
	{
		$mcategories[$dbCore->Record["troubleshootercatid"]] = $dbCore->Record;
		$mcategories[$dbCore->Record["troubleshootercatid"]]["title"] = iif(strlen($dbCore->Record["title"])>15, substr($dbCore->Record["title"],0,15)."..", $dbCore->Record["title"]);
		$mcategories[$dbCore->Record["troubleshootercatid"]]["link"] = "index.php?_m=troubleshooter&_a=managesteps&filter=1&troubleshootercatid=".intval($dbCore->Record["troubleshootercatid"]);
	}

	if (count($mcategories))
	{
		$template->assign("catlist", true);
		$template->assign("mcategories", $mcategories);
	}

	return true;
}
?>